﻿using Microsoft.AspNetCore.Mvc;
using STF.Blog.Common;
using STF.Blog.IService;
using STF.Blog.WebApp.Areas.ForumManage.Models.ArticleCateGory;
using X.PagedList;

namespace STF.Blog.WebApp.Areas.ForumManage.Controllers
{
    [Area("ForumManage")]
    public class ArticleCateGoryController : Controller
    {
        private IArticleCateGoryService _iacSvc;
        public ArticleCateGoryController(IArticleCateGoryService iacSvc)
        {
            _iacSvc = iacSvc;
        }

        [HttpGet]
        public async Task<IActionResult> Index(string search, int page = 1)
        {
            search = string.IsNullOrEmpty(search) ? "" : search;
            var data = await _iacSvc.GetByNameAsync(search);
            var AcList = data.Select(ac => new ArticleCateGoryListViewModel 
            {
                Id = ac.Id,
                Title = ac.Title,
                CreateTime = ac.CreateTime,
                UpdateTime = ac.UpdateTime
            });
            ViewBag.Search = search;
            var pages = await AcList.ToPagedListAsync(page,PageConfig.PageSize);
            return View(pages);
        }

        [HttpGet]
        public async Task<IActionResult> Add() 
        {
            return View(new ArticleCateGoryAddViewModel());
        }

        [HttpPost]
        public async Task<IActionResult> Add(ArticleCateGoryAddViewModel model) 
        {
            if (ModelState.IsValid) 
            {
                await _iacSvc.AddArticleCateGoryAsync(model.Title);
                return Redirect("~/ForumManage/ArticleCateGory/Index");
            }
            return View(model);
        }

        [HttpGet]
        public async Task<IActionResult> Update(int id) 
        {
            var data = await _iacSvc.GetByIdAsync(id);
            return View(new ArticleCateGoryUpdateViewModel 
            {
                Id = data.Id,
                Title = data.Title
            });
        }

        [HttpPost]
        public async Task<IActionResult> Update(ArticleCateGoryUpdateViewModel model) 
        {
            if (ModelState.IsValid) 
            {
                await _iacSvc.UpdateArticleCateGoryAsync(model.Id,model.Title);
                return Redirect("~/ForumManage/ArticleCateGory/Index");
            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> Delete(int id) 
        {
            await _iacSvc.PutTrashAsync(id);
            return Redirect("~/ForumManage/ArticleCateGory/Index");
        }

    }
}
